﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DCS.Business.Event;
using DCS.Business.Interface;
using DCS.Business.Manager;
using DCS.Business.Model;
using DCS.DataProvider;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using DCS.Configuration;
using System.Configuration;
using System.Threading;
using System.Diagnostics;


namespace AccessDownload
{
    public class Downloader : IFTPDownloader
    {
        #region members
        private static log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static SITAMessageManager manger;

        private Thread downThread; 

        #endregion

        #region Implete IFTPDownloader

        public void Init()
        {
            IUnityContainer container = new UnityContainer();

            UnityConfigurationSection config = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            config.Containers["Data"].Configure(container);

            IDataProvider provider = container.Resolve<IDataProvider>();

            manger = new SITAMessageManager(provider);

             downThread = new Thread(
                () =>
                {
                    while (true)
                    {
                        Thread.Sleep(int.Parse(ConfigurationManager.AppSettings["DownloadInterval"]));
                        this.ExecuteDownload();
                    }
                }
                );

        }

        public void ExecuteDetect()
        {
            this.ExecuteDownload();
        }

        public void ExecuteDownload()
        {
            string monthDir = DateTime.Now.AddMinutes(-10).ToString("yyyy-MM");

            try
            {
                //获取已获取的最大ID
                int maxID = manger.GetMaxSourceID(monthDir);

                Debug.WriteLine("the maxID is"+maxID.ToString());

                //获取新的message
                List<SITAMessage> messageList = manger.GetNewMessageList(maxID, monthDir, "GetMaxID");

                if (messageList != null && messageList.Count > 0)
                {
                    logger.InfoFormat("{0} messages need to Insert", messageList.Count);
                    manger.InsertSourceMessageList(messageList);
                }
            }
            catch(Exception e)
            {
                logger.Error(e);
            }

        }

        public void Exit()
        {
            downThread.Abort();
        }
        #endregion
    }
}
